package com.common.service.casemanage.impl;

import com.common.constants.Constants;
import com.common.converter.CaseConverter;
import com.common.converter.CaseProblemSituationConverter;
import com.common.converter.CaseQualityConverter;
import com.common.converter.CaseRiskConverter;
import com.common.entity.casemanage.*;
import com.common.entity.personal.QPersonalEntity;
import com.common.excel.BaseImportVo;
import com.common.excel.ExcelListener;
import com.common.excel.ExcelUtil;
import com.common.excel.ExcelValueCheckResp;
import com.common.excel.excelinfo.CaseExcelInfo;
import com.common.excel.listener.CaseExcelListener;
import com.common.global.BizException;
import com.common.global.BizServiceEnum;
import com.common.global.CommonEnum;
import com.common.query.QueryConditionVo;
import com.common.repository.casemanage.CaseProblemSituationRepository;
import com.common.repository.casemanage.CaseQualityFlowRepository;
import com.common.repository.casemanage.CaseRepository;
import com.common.repository.casemanage.CaseRiskRepository;
import com.common.requestvo.casemanage.CaseForQualityReqVo;
import com.common.requestvo.casemanage.CaseProblemSituationReqVo;
import com.common.requestvo.casemanage.CaseQualityFlowReqVo;
import com.common.requestvo.casemanage.CaseReqVo;
import com.common.service.casemanage.CaseService;
import com.common.vo.DateUtils;
import com.common.vo.casemanage.CaseForQualityFlowVo;
import com.common.vo.casemanage.CaseForRiskVo;
import com.common.vo.casemanage.CaseProblemSituationVo;
import com.common.vo.casemanage.CaseVo;
import com.querydsl.core.QueryResults;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author johnny
 * @create 2021-05-19 2:14 下午o
 **/
@Service
@Slf4j
@Transactional(rollbackOn = Exception.class)
public class CaseServiceImpl implements CaseService {

    private final JPAQueryFactory queryFactory;
    private final CaseRepository caseRepository;
    private final CaseRiskRepository caseRiskRepository;
    private final CaseQualityFlowRepository caseQualityFlowRepository;
    private final CaseProblemSituationRepository caseProblemSituationRepository;


    private final CaseExcelListener caseExcelListener;

    private QCaseEntity qCaseEntity = QCaseEntity.caseEntity;
    private QCaseQualityFlowEntity qCaseQualityFlowEntity = QCaseQualityFlowEntity.caseQualityFlowEntity;
    private QPersonalEntity qPersonalEntity = QPersonalEntity.personalEntity;


    public CaseServiceImpl(JPAQueryFactory queryFactory, CaseRepository caseRepository, CaseRiskRepository caseRiskRepository, CaseQualityFlowRepository caseQualityFlowRepository, CaseProblemSituationRepository caseProblemSituationRepository, CaseExcelListener caseExcelListener) {
        this.queryFactory = queryFactory;
        this.caseRepository = caseRepository;
        this.caseRiskRepository = caseRiskRepository;
        this.caseQualityFlowRepository = caseQualityFlowRepository;
        this.caseProblemSituationRepository = caseProblemSituationRepository;
        this.caseExcelListener = caseExcelListener;
    }


    @Override
    public Page<CaseVo> listByCondition(CaseReqVo caseReqVo, Pageable pageable) {
        List<CaseVo> list = new ArrayList<>();
        JPAQuery<CaseEntity> jpaQuery = queryFactory.select(qCaseEntity)
                .from(qCaseEntity)
                .offset(pageable.getPageNumber() * pageable.getPageSize())
                .limit(pageable.getPageSize());
        fillCondition(jpaQuery, caseReqVo);
        QueryResults<CaseEntity> queryResults = jpaQuery.fetchResults();
        queryResults.getResults().forEach(caseEntity -> {
            CaseVo caseVo = CaseConverter.INSTANCE.domain2vo(caseEntity);
            list.add(caseVo);
        });
        return new PageImpl<>(list, pageable, queryResults.getTotal());
    }

    @Override
    public void add(CaseVo caseVo) {

    }

    @Override
    public void edit(CaseVo caseVo) {

    }

    @Override
    public void delete(Long id) {
        if (caseRepository.existsById(id)) {
            caseRepository.deleteById(id);
        } else {
            throw new BizException(CommonEnum.ID_NOT_FIND_ENTITY);
        }
    }

    /**
     * 添加风险评估
     *
     * @param caseForRiskVo
     */
    @Override
    public void addRiskForCase(CaseForRiskVo caseForRiskVo) {
        caseForRiskVo.setId(null);
        if (caseRiskRepository.countByCaseNum(caseForRiskVo.getCaseNum()) > 0) {
            throw new BizException(BizServiceEnum.CASE_RISK_ONLY_ONE);
        }
        CaseEntity caseEntity = caseRepository.findById(caseForRiskVo.getCaseId()).orElse(null);
        if (caseEntity == null) {
            throw new BizException(BizServiceEnum.CAN_NOT_FIND_CASE);
        }
        CaseRiskEntity caseRiskEntity = CaseRiskConverter.INSTANCE.vo2domain(caseForRiskVo);
        caseRiskEntity.setCaseName(caseEntity.getCaseName());
        caseRiskEntity.setCaseNum(caseEntity.getCaseNum());
        caseRiskEntity.setPersonalId(caseEntity.getPersonalId());
        caseRiskRepository.save(caseRiskEntity);
    }

    @Override
    public void addQualityFlowForCase(CaseForQualityFlowVo caseForQualityFlowVo) {
        caseForQualityFlowVo.setId(null);
        CaseEntity caseEntity = caseRepository.findById(caseForQualityFlowVo.getCaseId()).orElse(null);
        if (caseEntity == null) {
            throw new BizException(BizServiceEnum.CAN_NOT_FIND_CASE);
        }
        CaseQualityFlowEntity caseQualityFlowEntity = CaseQualityConverter.INSTANCE.vo2domain(caseForQualityFlowVo);
        caseQualityFlowEntity.setCaseName(caseEntity.getCaseName());
        caseQualityFlowEntity.setCaseNum(caseEntity.getCaseNum());
        caseQualityFlowEntity.setPersonalId(caseEntity.getPersonalId());

        CaseProblemSituationEntity caseProblemEntity = caseProblemSituationRepository.findByIdAndType(caseForQualityFlowVo.getCaseProblemId(), Constants.PROBLEM);
        CaseProblemSituationEntity caseSituationEntity = caseProblemSituationRepository.findByIdAndType(caseForQualityFlowVo.getCaseSituationId(), Constants.SITUATION);

        if (caseProblemEntity == null || caseSituationEntity == null) {
            throw new BizException(BizServiceEnum.CAN_NOT_FIND_CASE_PROBLEM_SITUATION);
        }
        caseQualityFlowRepository.save(caseQualityFlowEntity);
    }

    /**
     * 根据 caseId 案件id  查询 案件下面的所有的 质量监控报告
     *
     * @param caseQualityFlowReqVo
     * @return
     */
    @Override
    public List<CaseForQualityFlowVo> findCaseQualityFlowList(CaseQualityFlowReqVo caseQualityFlowReqVo) {
        List<CaseForQualityFlowVo> caseForQualityFlowVos = new ArrayList<>();
        if (caseQualityFlowReqVo.getCaseId() != null && caseQualityFlowReqVo.getCaseId() != 0L
                && StringUtils.isNotEmpty(caseQualityFlowReqVo.getType())
                && Constants.QUALITY_FLOW_SET.contains(caseQualityFlowReqVo.getType())) {
            if (caseRepository.existsById(caseQualityFlowReqVo.getCaseId())) {
                queryFactory.select(qCaseQualityFlowEntity, qPersonalEntity.name)
                        .from(qCaseQualityFlowEntity)
                        .leftJoin(qPersonalEntity).on(qPersonalEntity.id.eq(qCaseQualityFlowEntity.personalId))
                        .where(qCaseQualityFlowEntity.type.eq(caseQualityFlowReqVo.getType()))
                        .fetch().forEach(tuple -> {
                    CaseQualityFlowEntity caseQualityFlowEntity = tuple.get(0, CaseQualityFlowEntity.class);
                    CaseForQualityFlowVo caseForQualityFlowVo = CaseQualityConverter.INSTANCE.domain2vo(caseQualityFlowEntity);
                    caseForQualityFlowVo.setPersonalName(tuple.get(1, String.class) == null ? StringUtils.EMPTY : tuple.get(1, String.class));
                    if (caseQualityFlowEntity != null) {
                        caseProblemSituationRepository.findById(caseQualityFlowEntity.getCaseProblemId())
                                .ifPresent(caseProblemEntity -> caseForQualityFlowVo.setCaseProblemName(caseProblemEntity.getName()));
                        caseProblemSituationRepository.findById(caseQualityFlowEntity.getCaseSituationId())
                                .ifPresent(caseSituationEntity -> caseForQualityFlowVo.setCaseSituationName(caseSituationEntity.getName()));
                    }
                    caseForQualityFlowVos.add(caseForQualityFlowVo);
                });
            } else {
                throw new BizException(BizServiceEnum.CAN_NOT_FIND_CASE);
            }
        } else {
            throw new BizException(CommonEnum.PARAMS_SHORTAGE);
        }
        return caseForQualityFlowVos;
    }

    /**
     * 编辑 质量监控信息
     *
     * @param caseForQualityFlowVo
     */
    @Override
    public void editQualityFlowForCase(CaseForQualityFlowVo caseForQualityFlowVo) {
        if (caseForQualityFlowVo.getId() == null || caseForQualityFlowVo.getId() == 0L) {
            throw new BizException(CommonEnum.ID_NOT_NULL);
        }
        if (StringUtils.isEmpty(caseForQualityFlowVo.getType()) ||
                !Constants.QUALITY_FLOW_SET.contains(caseForQualityFlowVo.getType())) {
            throw new BizException(BizServiceEnum.CASE_PROBLEM_SITUATION_TYPE_NULL);
        }
        CaseQualityFlowEntity caseQualityFlowEntity = caseQualityFlowRepository.findByIdAndType(caseForQualityFlowVo.getId(), caseForQualityFlowVo.getType());
        if (caseQualityFlowEntity == null) {
            throw new BizException(BizServiceEnum.CAN_NOT_FIND_CASE_QUALITY_FLOW);
        }
        CaseQualityFlowEntity newCaseQualityFlowEntity = CaseQualityConverter.INSTANCE.vo2domain(caseForQualityFlowVo);
        newCaseQualityFlowEntity.setCaseName(caseQualityFlowEntity.getCaseName());
        newCaseQualityFlowEntity.setCaseNum(caseQualityFlowEntity.getCaseNum());
        caseQualityFlowRepository.save(newCaseQualityFlowEntity);
    }

    @Override
    public void deleteCaseQualityFlowList(Long id) {
        if (caseQualityFlowRepository.existsById(id)) {
            caseQualityFlowRepository.deleteById(id);
        } else {
            throw new BizException(CommonEnum.ID_NOT_FIND_ENTITY);
        }
    }

    @Override
    public void editRiskForCase(CaseForRiskVo caseForRiskVo) {
        if (caseForRiskVo.getId() == null || caseForRiskVo.getId() == 0L) {
            throw new BizException(CommonEnum.ID_NOT_NULL);
        }
        if (caseRiskRepository.existsById(caseForRiskVo.getId())) {
            CaseRiskEntity caseRiskEntity = CaseRiskConverter.INSTANCE.vo2domain(caseForRiskVo);
            caseRiskRepository.save(caseRiskEntity);
        } else {
            throw new BizException(CommonEnum.ID_NOT_FIND_ENTITY);
        }
    }

    @Override
    public void deleteRiskForCase(Long id) {
        if (caseRiskRepository.existsById(id)) {
            caseRiskRepository.deleteById(id);
        } else {
            throw new BizException(CommonEnum.ID_NOT_FIND_ENTITY);
        }
    }

    @Override
    public CaseForRiskVo findRiskForCaseByCaseId(Long caseId) {
        if (caseId != null && caseId != 0L) {
            if (caseRepository.existsById(caseId)) {
                CaseRiskEntity caseRiskEntity = caseRiskRepository.findByCaseId(caseId);
                return CaseRiskConverter.INSTANCE.domain2vo(caseRiskEntity);
            } else {
                throw new BizException(CommonEnum.ID_NOT_FIND_ENTITY);
            }
        } else {
            throw new BizException(CommonEnum.ID_NOT_NULL);
        }
    }

    @Override
    public Long findCaseQualityFlowCountByPersonalId(Long personalId) {
        if (personalId != null && personalId != 0L) {
            return caseQualityFlowRepository.countByPersonalId(personalId);
        } else {
            throw new BizException(BizServiceEnum.FIND_NOT_PERSONAL_INFO);
        }
    }

    /**
     * 删除  问题
     * 会把下面的情形都删了
     *
     * @param id
     */
    @Override
    public void deleteProblem(Long id) {
        if (caseProblemSituationRepository.existsById(id)) {
            caseProblemSituationRepository.deleteByParentIdAndType(id, Constants.SITUATION);
            caseProblemSituationRepository.deleteById(id);
        } else {
            throw new BizException(CommonEnum.ID_NOT_FIND_ENTITY);
        }
    }

    @Override
    public void deleteSituation(Long id) {
        if (caseProblemSituationRepository.existsById(id)) {
            caseProblemSituationRepository.deleteByIdAndType(id, Constants.SITUATION);
        } else {
            throw new BizException(CommonEnum.ID_NOT_FIND_ENTITY);
        }
    }

    /**
     * 根据 personalId 查询 风险案件
     *
     * @param personalId
     * @return
     */
    @Override
    public Long findCaseRiskCountByPersonalId(Long personalId) {
        if (personalId != null && personalId != 0L) {
            return caseRiskRepository.countByPersonalId(personalId);
        } else {
            throw new BizException(BizServiceEnum.FIND_NOT_PERSONAL_INFO);
        }
    }

    /**
     * 查询 所有的 问题
     *
     * @return
     */
    @Override
    public List<CaseProblemSituationVo> findAllCaseProblem() {

        List<CaseProblemSituationVo> caseProblemSituationVos = new ArrayList<>();
        caseProblemSituationRepository.findByParentIdIsNullAndTypeOrderByIdDesc(Constants.PROBLEM).forEach(caseProblemSituationEntity -> {
            CaseProblemSituationVo caseProblemSituationVo = CaseProblemSituationConverter.INSTANCE.domain2vo(caseProblemSituationEntity);
            fillChildrenCaseProblemSituationVo(caseProblemSituationVo);
            caseProblemSituationVos.add(caseProblemSituationVo);
        });
        return caseProblemSituationVos;
    }

    @Override
    public List<CaseProblemSituationVo> findCaseSituationByProblemId(Long problemId) {
        List<CaseProblemSituationVo> caseProblemSituationVos = new ArrayList<>();

        List<CaseProblemSituationEntity> caseProblemSituationEntityList = caseProblemSituationRepository.findByParentIdAndTypeOrderByIdDesc(problemId, Constants.SITUATION);
        caseProblemSituationEntityList.forEach(caseProblemSituationEntity -> {
            CaseProblemSituationVo caseProblemSituationVo = CaseProblemSituationConverter.INSTANCE.domain2vo(caseProblemSituationEntity);
            caseProblemSituationVos.add(caseProblemSituationVo);
        });
        return caseProblemSituationVos;
    }

    @Override
    public void addCaseProblemSituation(CaseProblemSituationReqVo caseProblemSituationReqVo) {
        caseProblemSituationReqVo.setId(null);
        addEditCaseProblemSituation(caseProblemSituationReqVo);
    }

    @Override
    public void editCaseProblemSituation(CaseProblemSituationReqVo caseProblemSituationReqVo) {
        if (caseProblemSituationReqVo.getId() == null) {
            throw new BizException(CommonEnum.ID_NOT_NULL);
        }
        addEditCaseProblemSituation(caseProblemSituationReqVo);
    }


    private void addEditCaseProblemSituation(CaseProblemSituationReqVo caseProblemSituationReqVo) {
        if (StringUtils.isNotEmpty(caseProblemSituationReqVo.getType())) {
            if (caseProblemSituationReqVo.getType().equals(Constants.SITUATION)) {
                if (caseProblemSituationReqVo.getParentId() == null || caseProblemSituationReqVo.getParentId() == 0L) {
                    //当是 情形时候 需要选择 问题作为父Id
                    throw new BizException(BizServiceEnum.PARENT_ID_NOT_NULL);
                } else {
                    CaseProblemSituationEntity parentEntity = caseProblemSituationRepository.findByIdAndType(caseProblemSituationReqVo.getParentId(), Constants.PROBLEM);
                    if (parentEntity == null) {
                        throw new BizException(BizServiceEnum.CAN_NOT_FIND_PARENT_TYPE);
                    } else if (parentEntity.getType().equals(Constants.SITUATION)) {
                        throw new BizException(BizServiceEnum.CAN_NOT_PARENT_IS_SITUATION_TYPE);
                    }
                }
            }
            //做新增/修改
            CaseProblemSituationEntity caseProblemSituationEntity = CaseProblemSituationConverter.INSTANCE.vo2domain(caseProblemSituationReqVo);
            caseProblemSituationRepository.save(caseProblemSituationEntity);
        } else {
            //必须指定类型type
            throw new BizException(BizServiceEnum.CASE_PROBLEM_SITUATION_TYPE_NULL);
        }
    }

    /**
     * 根据 问题Id 查询 问题下面的情形
     *
     * @param caseProblemSituationVo
     */
    private void fillChildrenCaseProblemSituationVo(CaseProblemSituationVo caseProblemSituationVo) {
        List<CaseProblemSituationEntity> caseProblemSituationEntityList = getChildrenCaseProblemSituationVo(caseProblemSituationVo.getId());
        if (!CollectionUtils.isEmpty(caseProblemSituationEntityList)) {
            caseProblemSituationVo.setChildren(caseProblemSituationEntityList.stream().map(caseProblemSituationEntity -> {
                CaseProblemSituationVo childrenCaseProblemSituationVo = CaseProblemSituationConverter.INSTANCE.domain2vo(caseProblemSituationEntity);
                BeanUtils.copyProperties(caseProblemSituationEntity, childrenCaseProblemSituationVo);
                fillChildrenCaseProblemSituationVo(childrenCaseProblemSituationVo);
                return childrenCaseProblemSituationVo;
            }).collect(Collectors.toList()));
        }
    }

    private List<CaseProblemSituationEntity> getChildrenCaseProblemSituationVo(Long id) {
        return caseProblemSituationRepository.findByParentIdAndTypeOrderByIdDesc(id, Constants.PROBLEM);
    }

    /**
     * 办案质量 里面的 相关案件列表接口
     *
     * @param caseForQualityReqVo
     * @param pageable
     * @return
     */
    @Override
    public Page<CaseVo> listByConditionForQuality(CaseForQualityReqVo caseForQualityReqVo, Pageable pageable) {
        List<CaseVo> list = new ArrayList<>();
        JPAQuery<CaseEntity> jpaQuery = queryFactory.select(qCaseEntity)
                .from(qCaseEntity)
                .offset(pageable.getPageNumber() * pageable.getPageSize())
                .limit(pageable.getPageSize())
                //需要的条件是  办结案件日期不等于空
                .where(qCaseEntity.caseEndDate.isNotNull());
        fillConditionForQuality(jpaQuery, caseForQualityReqVo);
        QueryResults<CaseEntity> queryResults = jpaQuery.fetchResults();
        queryResults.getResults().forEach(caseEntity -> {
            CaseVo caseVo = CaseConverter.INSTANCE.domain2vo(caseEntity);
            list.add(caseVo);
        });
        return new PageImpl<>(list, pageable, queryResults.getTotal());
    }


    private void fillConditionForQuality(JPAQuery<CaseEntity> jpaQuery, CaseForQualityReqVo caseForQualityReqVo) {
        if (StringUtils.isNotEmpty(caseForQualityReqVo.getCaseName())) {
            jpaQuery.where(qCaseEntity.caseName.like("%" + caseForQualityReqVo.getCaseName() + "%"));
        }
        if (StringUtils.isNotEmpty(caseForQualityReqVo.getCaseNum())) {
            String decode = null;
            try {
                decode = URLDecoder.decode(caseForQualityReqVo.getCaseNum(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            jpaQuery.where(qCaseEntity.caseNum.like("%" + decode + "%"));
        }
        if (StringUtils.isNotEmpty(caseForQualityReqVo.getCaseType())) {
            jpaQuery.where(qCaseEntity.caseType.eq(caseForQualityReqVo.getCaseType()));
        }
        if (caseForQualityReqVo.getPersonalId() != null && caseForQualityReqVo.getPersonalId() != 0L) {
            jpaQuery.where(qCaseEntity.personalId.eq(caseForQualityReqVo.getPersonalId()));
        }
        if (caseForQualityReqVo.getDepartmentId() != null && caseForQualityReqVo.getDepartmentId() != 0L) {
            jpaQuery.where(qCaseEntity.caseDepartmentId.eq(caseForQualityReqVo.getDepartmentId()));
        }
    }

    @Override
    public void fillCondition(JPAQuery<CaseEntity> jpaQuery, QueryConditionVo queryConditionVo) {
        CaseReqVo caseReqVo = (CaseReqVo) queryConditionVo;
        if (StringUtils.isNotEmpty(caseReqVo.getCaseNum())) {
            String decode = null;
            try {
                decode = URLDecoder.decode(caseReqVo.getCaseNum(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            jpaQuery.where(qCaseEntity.caseNum.like("%" + decode + "%"));
        }
        if (StringUtils.isNotEmpty(caseReqVo.getCaseName())) {
            jpaQuery.where(qCaseEntity.caseName.like("%" + caseReqVo.getCaseName() + "%"));
        }
        if (StringUtils.isNotEmpty(caseReqVo.getCaseType())) {
            jpaQuery.where(qCaseEntity.caseType.eq(caseReqVo.getCaseType()));
        }
        if (StringUtils.isNotEmpty(caseReqVo.getPersonalName())) {
            jpaQuery.where(qCaseEntity.personalName.like("%" + caseReqVo.getPersonalName() + "%"));
        }
        //办案日期 start
        if (StringUtils.isNotEmpty(caseReqVo.getCaseHandleDateStart())) {
            jpaQuery.where(qCaseEntity.caseHandleDate.after(DateUtils.formatDate(caseReqVo.getCaseHandleDateStart(), DateUtils.DATE_EXCEL_FORMAT)));
        }
        //办案日期 end
        if (StringUtils.isNotEmpty(caseReqVo.getCaseHandleDateEnd())) {
            jpaQuery.where(qCaseEntity.caseHandleDate.before(DateUtils.formatDate(caseReqVo.getCaseHandleDateEnd(), DateUtils.DATE_EXCEL_FORMAT)));
        }
        //办结日期 start
        if (StringUtils.isNotEmpty(caseReqVo.getCaseEndDateStart())) {
            jpaQuery.where(qCaseEntity.caseEndDate.after(DateUtils.formatDate(caseReqVo.getCaseEndDateStart(), DateUtils.DATE_EXCEL_FORMAT)));
        }
        //办结日期 end
        if (StringUtils.isNotEmpty(caseReqVo.getCaseEndDateEnd())) {
            jpaQuery.where(qCaseEntity.caseEndDate.before(DateUtils.formatDate(caseReqVo.getCaseEndDateEnd(), DateUtils.DATE_EXCEL_FORMAT)));
        }
        //犯罪类型
        if (StringUtils.isNotEmpty(caseReqVo.getCaseCrimeType())) {
            jpaQuery.where(qCaseEntity.caseCrimeType.like("%" + caseReqVo.getCaseCrimeType() + "%"));
        }
        //案件类型
        if (StringUtils.isNotEmpty(caseReqVo.getCaseType())) {
            jpaQuery.where(qCaseEntity.caseType.eq(caseReqVo.getCaseType()));
        }
        //是否公开
        if (StringUtils.isNotEmpty(caseReqVo.getCaseIsPublic())) {
            jpaQuery.where(qCaseEntity.caseIsPublic.eq(caseReqVo.getCaseIsPublic()));
        }

        if (caseReqVo.getCaseDepartmentId() != null && caseReqVo.getCaseDepartmentId() != 0L) {
            jpaQuery.where(qCaseEntity.caseDepartmentId.eq(caseReqVo.getCaseDepartmentId()));
        }
        if (StringUtils.isNotEmpty(caseReqVo.getCaseStatus())) {
            jpaQuery.where(qCaseEntity.caseStatus.eq(caseReqVo.getCaseStatus()));
        }
    }


    /**
     * 导入案件
     *
     * @param baseImportVo
     * @return
     */
    @Override
    public ExcelValueCheckResp importFile(BaseImportVo baseImportVo) {
        log.info("【start import case】");
        List<CaseEntity> list = new ArrayList<>();
        log.info("【开始读取 案件 Excel sheet】");
        ExcelUtil.readExcel(baseImportVo.getFile(), new CaseExcelInfo(), 1,
                caseExcelListener);
        if (ExcelListener.excelValueCheckResp().getErrorInfoRespMap().size() == 0) {
            List<Object> dataList = ExcelListener.getDatas();

            List<String> caseNumList = dataList.stream().map(object -> (CaseExcelInfo) object).collect(Collectors.toList())
                    .stream().map(CaseExcelInfo::getCaseNum).collect(Collectors.toList());

            List<Long> existCaseIdList = queryFactory.select(qCaseEntity.id)
                    .from(qCaseEntity)
                    .where(qCaseEntity.caseNum.in(caseNumList)).fetch();
            if (CollectionUtils.isNotEmpty(existCaseIdList)) {
                queryFactory.delete(qCaseEntity)
                        .where(qCaseEntity.id.in(existCaseIdList))
                        .execute();
            }
            dataList.forEach(info -> {
                CaseExcelInfo caseExcelInfo = (CaseExcelInfo) info;
                CaseEntity caseEntity = CaseConverter.INSTANCE.excel2domain(caseExcelInfo);
                caseEntity.setCreateBy(baseImportVo.getCreateBy());
                list.add(caseEntity);
            });

            caseRepository.saveAll(list);
        }
        log.info("【end import case】");
        return ExcelListener.excelValueCheckResp();
    }
}